export default function(coder: any) {


  coder['text'] = function(block: any) {
    let val = block.getFieldValue('TEXT')
    var code = Blockly.isNumber(val)? val: coder.quote_(val);
    return [code, coder.ORDER_ATOMIC];
  };

  /**
   * Enclose the provided value in 'String(...)' function.
   * Leave string literals alone.
   * @param {string} value Code evaluating to a value.
   * @return {string} Code evaluating to a string.
   * @private
   */
  coder.text.forceString_ = function(value: any) {
    if (coder.text.forceString_.strRegExp.test(value)) {
      return value;
    }
    return 'String(' + value + ')';
  };

  /**
   * Regular expression to detect a single-quoted string literal.
   */
  coder.text.forceString_.strRegExp = /^\s*'([^']|\\')*'\s*$/;

  coder['text_join'] = function(block: any) {
    // Create a string made up of any number of elements of any type.
    switch (block.itemCount_) {
      case 0:
        return ['\'\'', coder.ORDER_ATOMIC];
      case 1:
        var element = coder.valueToCode(block, 'ADD0',
            coder.ORDER_NONE) || '\'\'';
        var code = coder.text.forceString_(element);
        return [code, coder.ORDER_FUNCTION_CALL];
      case 2:
        var element0 = coder.valueToCode(block, 'ADD0',
            coder.ORDER_NONE) || '\'\'';
        var element1 = coder.valueToCode(block, 'ADD1',
            coder.ORDER_NONE) || '\'\'';
        var code: any = coder.text.forceString_(element0) + ' + ' +
            coder.text.forceString_(element1);
        return [code, coder.ORDER_ADDITION];
      default:
        var elements = new Array(block.itemCount_);
        for (var i = 0; i < block.itemCount_; i++) {
          elements[i] = coder.valueToCode(block, 'ADD' + i,
              coder.ORDER_COMMA) || '\'\'';
        }
        var code: any = '[' + elements.join(',') + '].join(\'\')';
        return [code, coder.ORDER_FUNCTION_CALL];
    }
  };

  coder['text_append'] = function(block: any) {
    // Append to a variable in place.
    var varName = coder.variableDB_.getName(
        block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
    var value = coder.valueToCode(block, 'TEXT',
        coder.ORDER_NONE) || '\'\'';
    return varName + ' += ' + coder.text.forceString_(value) + ';\n';
  };

  coder['text_length'] = function(block: any) {
    // String or array length.
    var text = coder.valueToCode(block, 'VALUE',
        coder.ORDER_FUNCTION_CALL) || '\'\'';
    return [text + '.length', coder.ORDER_MEMBER];
  };

  coder['text_isEmpty'] = function(block: any) {
    // Is the string null or array empty?
    var text = coder.valueToCode(block, 'VALUE',
        coder.ORDER_MEMBER) || '\'\'';
    return ['!' + text + '.length', coder.ORDER_LOGICAL_NOT];
  };

  coder['text_indexOf'] = function(block: any) {
    // Search the text for a substring.
    var operator = block.getFieldValue('END') == 'FIRST' ?
        'indexOf' : 'lastIndexOf';
    var substring = coder.valueToCode(block, 'FIND',
        coder.ORDER_NONE) || '\'\'';
    var text = coder.valueToCode(block, 'VALUE',
        coder.ORDER_MEMBER) || '\'\'';
    var code = text + '.' + operator + '(' + substring + ')';
    // Adjust index if using one-based indices.
    if (block.workspace.options.oneBasedIndex) {
      return [code + ' + 1', coder.ORDER_ADDITION];
    }
    return [code, coder.ORDER_FUNCTION_CALL];
  };

  coder['text_charAt'] = function(block: any) {
    // Get letter at index.
    // Note: Until January 2013 this block did not have the WHERE input.
    var where = block.getFieldValue('WHERE') || 'FROM_START';
    var textOrder = (where == 'RANDOM') ? coder.ORDER_NONE :
        coder.ORDER_MEMBER;
    var text = coder.valueToCode(block, 'VALUE',
        textOrder) || '\'\'';
    switch (where) {
      case 'FIRST':
        var code = text + '.charAt(0)';
        return [code, coder.ORDER_FUNCTION_CALL];
      case 'LAST':
        var code = text + '.slice(-1)';
        return [code, coder.ORDER_FUNCTION_CALL];
      case 'FROM_START':
        var at = coder.getAdjusted(block, 'AT');
        // Adjust index if using one-based indices.
        var code = text + '.charAt(' + at + ')';
        return [code, coder.ORDER_FUNCTION_CALL];
      case 'FROM_END':
        var at = coder.getAdjusted(block, 'AT', 1, true);
        var code = text + '.slice(' + at + ').charAt(0)';
        return [code, coder.ORDER_FUNCTION_CALL];
      case 'RANDOM':
        var functionName = coder.provideFunction_(
            'textRandomLetter',
            ['function ' + coder.FUNCTION_NAME_PLACEHOLDER_ +
                '(text) {',
            '  var x = Math.floor(Math.random() * text.length);',
            '  return text[x];',
            '}']);
        var code = functionName + '(' + text + ')';
        return [code, coder.ORDER_FUNCTION_CALL];
    }
    throw Error('Unhandled option (text_charAt).');
  };

  /**
   * Returns an expression calculating the index into a string.
   * @param {string} stringName Name of the string, used to calculate length.
   * @param {string} where The method of indexing, selected by dropdown in Blockly
   * @param {string=} opt_at The optional offset when indexing from start/end.
   * @return {string} Index expression.
   * @private
   */
  coder.text.getIndex_ = function(stringName: string, where: string, opt_at: string) {
    if (where == 'FIRST') {
      return '0';
    } else if (where == 'FROM_END') {
      return stringName + '.length - 1 - ' + opt_at;
    } else if (where == 'LAST') {
      return stringName + '.length - 1';
    } else {
      return opt_at;
    }
  };

  coder['text_getSubstring'] = function(block: any) {
    // Get substring.
    var text = coder.valueToCode(block, 'STRING',
        coder.ORDER_FUNCTION_CALL) || '\'\'';
    var where1 = block.getFieldValue('WHERE1');
    var where2 = block.getFieldValue('WHERE2');
    if (where1 == 'FIRST' && where2 == 'LAST') {
      var code = text;
    } else if (text.match(/^'?\w+'?$/) ||
        (where1 != 'FROM_END' && where1 != 'LAST' &&
        where2 != 'FROM_END' && where2 != 'LAST')) {
      // If the text is a variable or literal or doesn't require a call for
      // length, don't generate a helper function.
      switch (where1) {
        case 'FROM_START':
          var at1: any = coder.getAdjusted(block, 'AT1');
          break;
        case 'FROM_END':
          var at1: any = coder.getAdjusted(block, 'AT1', 1, false,
              coder.ORDER_SUBTRACTION);
          at1 = text + '.length - ' + at1;
          break;
        case 'FIRST':
          var at1: any = '0';
          break;
        default:
          throw Error('Unhandled option (text_getSubstring).');
      }
      switch (where2) {
        case 'FROM_START':
          var at2 = coder.getAdjusted(block, 'AT2', 1);
          break;
        case 'FROM_END':
          var at2: any = coder.getAdjusted(block, 'AT2', 0, false,
              coder.ORDER_SUBTRACTION);
          at2 = text + '.length - ' + at2;
          break;
        case 'LAST':
          var at2: any = text + '.length';
          break;
        default:
          throw Error('Unhandled option (text_getSubstring).');
      }
      code = text + '.slice(' + at1 + ', ' + at2 + ')';
    } else {
      var at1 = coder.getAdjusted(block, 'AT1');
      var at2 = coder.getAdjusted(block, 'AT2');
      var getIndex_ = coder.text.getIndex_;
      var wherePascalCase: any = {'FIRST': 'First', 'LAST': 'Last',
        'FROM_START': 'FromStart', 'FROM_END': 'FromEnd'};
      var functionName = coder.provideFunction_(
          'subsequence' + wherePascalCase[where1] + wherePascalCase[where2],
          ['function ' + coder.FUNCTION_NAME_PLACEHOLDER_ +
          '(sequence' +
          // The value for 'FROM_END' and'FROM_START' depends on `at` so
          // we add it as a parameter.
          ((where1 == 'FROM_END' || where1 == 'FROM_START') ? ', at1' : '') +
          ((where2 == 'FROM_END' || where2 == 'FROM_START') ? ', at2' : '') +
          ') {',
            '  var start = ' + getIndex_('sequence', where1, 'at1') + ';',
            '  var end = ' + getIndex_('sequence', where2, 'at2') + ' + 1;',
            '  return sequence.slice(start, end);',
            '}']);
      var code: any = functionName + '(' + text +
          // The value for 'FROM_END' and 'FROM_START' depends on `at` so we
          // pass it.
          ((where1 == 'FROM_END' || where1 == 'FROM_START') ? ', ' + at1 : '') +
          ((where2 == 'FROM_END' || where2 == 'FROM_START') ? ', ' + at2 : '') +
          ')';
    }
    return [code, coder.ORDER_FUNCTION_CALL];
  };

  coder['text_changeCase'] = function(block: any) {
    // Change capitalization.
    var OPERATORS: any = {
      'UPPERCASE': '.toUpperCase()',
      'LOWERCASE': '.toLowerCase()',
      'TITLECASE': null
    };
    var operator = OPERATORS[block.getFieldValue('CASE')];
    var textOrder = operator ? coder.ORDER_MEMBER :
        coder.ORDER_NONE;
    var text = coder.valueToCode(block, 'TEXT',
        textOrder) || '\'\'';
    if (operator) {
      // Upper and lower case are functions built into JavaScript.
      var code = text + operator;
    } else {
      // Title case is not a native JavaScript function.  Define one.
      var functionName = coder.provideFunction_(
          'textToTitleCase',
          ['function ' + coder.FUNCTION_NAME_PLACEHOLDER_ +
              '(str) {',
          '  return str.replace(/\\S+/g,',
          '      function(txt) {return txt[0].toUpperCase() + ' +
              'txt.substring(1).toLowerCase();});',
          '}']);
      var code: any = functionName + '(' + text + ')';
    }
    return [code, coder.ORDER_FUNCTION_CALL];
  };

  coder['text_trim'] = function(block: any) {
    // Trim spaces.
    var OPERATORS: any = {
      'LEFT': ".replace(/^[\\s\\xa0]+/, '')",
      'RIGHT': ".replace(/[\\s\\xa0]+$/, '')",
      'BOTH': '.trim()'
    };
    var operator = OPERATORS[block.getFieldValue('MODE')];
    var text = coder.valueToCode(block, 'TEXT',
        coder.ORDER_MEMBER) || '\'\'';
    return [text + operator, coder.ORDER_FUNCTION_CALL];
  };

  coder['text_print'] = function(block: any) {
    // Print statement.
    var msg = coder.valueToCode(block, 'TEXT',
        coder.ORDER_NONE) || '\'\'';
    return 'window.alert(' + msg + ');\n';
  };

  coder['text_prompt_ext'] = function(block: any) {
    // Prompt function.
    if (block.getField('TEXT')) {
      // Internal message.
      var msg = coder.quote_(block.getFieldValue('TEXT'));
    } else {
      // External message.
      var msg = coder.valueToCode(block, 'TEXT',
          coder.ORDER_NONE) || '\'\'';
    }
    var code = 'window.prompt(' + msg + ')';
    var toNumber = block.getFieldValue('TYPE') == 'NUMBER';
    if (toNumber) {
      code = 'parseFloat(' + code + ')';
    }
    return [code, coder.ORDER_FUNCTION_CALL];
  };

  coder['text_prompt'] = coder['text_prompt_ext'];

  coder['text_count'] = function(block: any) {
    var text = coder.valueToCode(block, 'TEXT',
        coder.ORDER_MEMBER) || '\'\'';
    var sub = coder.valueToCode(block, 'SUB',
        coder.ORDER_NONE) || '\'\'';
    var functionName = coder.provideFunction_(
        'textCount',
        ['function ' + coder.FUNCTION_NAME_PLACEHOLDER_ +
            '(haystack, needle) {',
        '  if (needle.length === 0) {',
        '    return haystack.length + 1;',
        '  } else {',
        '    return haystack.split(needle).length - 1;',
        '  }',
        '}']);
    var code = functionName + '(' + text + ', ' + sub + ')';
    return [code, coder.ORDER_SUBTRACTION];
  };

  coder['text_replace'] = function(block: any) {
    var text = coder.valueToCode(block, 'TEXT',
        coder.ORDER_MEMBER) || '\'\'';
    var from = coder.valueToCode(block, 'FROM',
        coder.ORDER_NONE) || '\'\'';
    var to = coder.valueToCode(block, 'TO',
        coder.ORDER_NONE) || '\'\'';
    // The regex escaping code below is taken from the implementation of
    // goog.string.regExpEscape.
    var functionName = coder.provideFunction_(
        'textReplace',
        ['function ' + coder.FUNCTION_NAME_PLACEHOLDER_ +
            '(haystack, needle, replacement) {',
        '  needle = ' +
            'needle.replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g,"\\\\$1")',
        '                 .replace(/\\x08/g,"\\\\x08");',
        '  return haystack.replace(new RegExp(needle, \'g\'), replacement);',
        '}']);
    var code = functionName + '(' + text + ', ' + from + ', ' + to + ')';
    return [code, coder.ORDER_MEMBER];
  };

  coder['text_reverse'] = function(block: any) {
    var text = coder.valueToCode(block, 'TEXT',
        coder.ORDER_MEMBER) || '\'\'';
    var code = text + '.split(\'\').reverse().join(\'\')';
    return [code, coder.ORDER_MEMBER];
  };

}